<?php  if ( ! defined('APPPATH')) exit('No direct script access allowed');
/**
 *      [PinTuXiu] (C)2001-2099 ONightjar.com Pintuxiu.com.
 *      This is NOT a freeware, use is subject to license terms
*/
define('PAGESIZE', 20);
ini_set("memory_limit","200M");
class admin_controller extends PZ_Controller{

	public function __construct() {
		parent::__construct();
	}

	public function beforeAction(){
		load_helper('global');
		$uapi = load_api('user');
		$api = load_api('setting');
		$stylesetting = $api->getStyleSetting();
		$this->theme = 'admin';
		$this->thcolor = 'default';
		$this->isadmin = $uapi->isAdmin();
		$this->cuser = $uapi->getUserInfo();
		if(!$this->isadmin&&$this->method!='login'){
			$this->jump(site_url('admin/login'));
			return false;
		}
		$this->cuser = $uapi->getUserInfo();
		$this->settings = $api->getGlobalSetting();
		$this->language = config_item('language');

		$modules = $api->getSetting('modules');
		if($modules){
			foreach ($modules as $key=>$d) {
				if($d['console']) $modules[$key]['console'] = load_api($key.'/'.$key.'_admin')->console;
			}
			$this->modules = $modules;
		}else{
			$this->modules = array();
		}
		return true;
	}

	public function login(){
		if($this->isadmin){
			$this->jump(site_url('admin/index'));
			return;
		}
		$userapi = load_api('user');
		if($data['email'] = $this->param('email')){
			$data['password'] = $this->param('password');
			if($result = $userapi->adminlogin($data)){
				$this->jump(site_url('admin/index'));
				return;
			}
		}
		$this->output('login/index');
	}

	public function logout(){
		load_api('user')->logout();
		$this->jump(site_url('admin/login'));
	}

	public function index(){
		$this->output('index');
	}


	public function dashboard_center(){
		$this->serverinfo  = PHP_OS.' / PHP v'.PHP_VERSION;
		$this->serverinfo .= @ini_get('safe_mode') ? ' Safe Mode' : NULL;
		$this->serversoft = $_SERVER['SERVER_SOFTWARE'];
		$this->pzversion = config_item('pzversion','version');
		$this->pzrelease = config_item('pzrelease','version');
		$admindb = load_db('admin');
		$this->dbversion = $admindb->dbversion();
		$dbsize = $admindb->dbsize();
		$this->dbsize = $dbsize ? sizecount($dbsize) : $lang['unknown'];
		if(@ini_get('file_uploads')) {
			$this->fileupload = ini_get('upload_max_filesize');
		} else {
			$this->fileupload = '<font color="red">NO</font>';
		}

		$this->output('dashboard/center');
	}

	public function basicinfo(){
		$api = load_api('setting');
		$setting = $api->getSetting('global');
		$act=$this->param('act');
		if($act=='save'){
			$postvar = array('site_name'=>lang('default_sitename','admin'),'site_domain'=>lang('default_sitedomain','admin'),'site_beian'=>'','site_email'=>'','siteclosed'=>'0');
			foreach ($postvar as $key=>$default){
				$setting[$key] = $this->param($key,$default);
			}

			$setting['site_analyze_code'] = $this->param('site_analyze_code','',false);
			$api->updateSetting('global',$setting);
			$this->redirect(site_url('admin/basicinfo'), lang('operate_success','admin'));
			return;
		}
		$this->setting = $setting;
		load_helper('file');
		$locals_dir = APPPATH.'language/';
		$file_list = get_dir_file_info($locals_dir);
		$dir = array();
		foreach ($file_list as $d) {
			$dir[] = $d['name'];
		}
		$this->dirs = $dir;

		$this->output('global/basicinfo');
	}

	public function basicmessage(){
		$api = load_api('setting');
		$setting = $api->getSetting('message');
		$act=$this->param('act');
		if($act=='save'){
			$postvar = array('site_closed_heading'=>lang('site_closed_heading','tip'),'site_closed_content'=>lang('site_closed_content','tip'));
			foreach ($postvar as $key=>$default){
				$setting[$key] = $this->param($key,$default);
			}
			$api->updateSetting('message',$setting);
			$this->redirect(site_url('admin/basicmessage'), lang('operate_success','admin'));
			return;
		}
		$this->setting = $setting;
		$this->output('global/basicmessage');
	}

	public function basicaccess(){
		$api = load_api('setting');
		$settingkey = 'register';
		$setting = $api->getSetting($settingkey);
		$act=$this->param('act');
		if($act=='save'){
			$setting['emailopen'] = $this->param('emailopen','0');//no email user
			$setting['verify_type'] = $this->param('verify_type','no');//no email user
			$api->updateSetting($settingkey,$setting);
			$this->redirect(site_url('admin/basicaccess'), lang('operate_success','admin'));
			return;
		}
		$this->setting = $setting;
		$this->output('global/basicaccess');
	}

	public function basicpzglobal(){
		$api = load_api('setting');
		$setting = $api->getSetting('pzglobal');
		$act=$this->param('act');
		if($act=='save'){
			$postvar = array('timeoffset'=>'8','pathinfo_support'=>'1','url_rewrite'=>'0','compress_output'=>'0','language'=>'zh_cn','default_module'=>'welcome/index','date_format'=>'Y-m-d');
			if($this->param('pathinfo_support')!=$setting['pathinfo_support']||$this->param('url_rewrite')!=$setting['url_rewrite']){
				load_helper('file');
				//delete_files(BASEPATH.'data/template/');
				delete_files(BASEPATH.'data/template/', FALSE, 0, 'php');
				delete_files(BASEPATH.'data/template/', FALSE, 0, 'js');
			}

			load_helper('configfile');
			$default_config = $config = array();
			$default_configfile = BASEPATH.'config/global.php';

			if(!file_exists($default_configfile)) {
				exit('global.php was lost, please reupload this file.');
			} else {
				include $default_configfile;
				$default_config = $config;
			}

			foreach ($postvar as $key=>$default){
				$setting[$key] = $config[$key] = $this->param($key,$default);

			}
			$api->updateSetting('pzglobal',$setting);
			save_config_file(BASEPATH.'config/global.php', $config, $default_config);
			$this->redirect(site_url('admin/basicpzglobal'), lang('operate_success','admin'));
			return;
		}
		load_helper('file');
		$locals_dir = APPPATH.'language/';
		$file_list = get_dir_file_info($locals_dir);
		$dir = array();
		foreach ($file_list as $d) {
			$dir[] = $d['name'];
		}
		$this->dirs = $dir;
		$this->timezones = lang('time_zone_list','admin');
		$this->setting = $setting;
		$this->output('global/basicpzglobal');
	}

	public function basicoptimizer(){
		$api = load_api('setting');
		$setting = $api->getSetting('optimizer');
		$act=$this->param('act');
		if($act=='save'){
			$postvar = array('like_search'=>'0','cachetime_default'=>500,'cachetime_homealbum'=>500,'cachetime_homeuser'=>500,'cachetime_footercount'=>500);
			foreach ($postvar as $key=>$default){
				$setting[$key] = $this->param($key,$default);
			}
			$api->updateSetting('optimizer',$setting);
			$this->redirect(site_url('admin/basicoptimizer'), lang('operate_success','admin'));
			return;
		}
		$this->setting = $setting;
		$this->output('global/basicoptimizer');
	}

	public function basicseo(){
		$api = load_api('setting');
		$this->type = $type = $this->param('type','home');
		$settingkey = 'seo-'.$type;
		$setting = $api->getSetting($settingkey);
		$act=$this->param('act');
		if($act=='save'){
			$postvar = array('seo_title'=>lang('official_softname_cn').' '.lang('official_softname'),'seo_keyword'=>lang('official_softname_cn'),'seo_description'=>'');
			foreach ($postvar as $key=>$default){
				$setting[$key] = $this->param($key,$default);
			}
			$api->updateSetting($settingkey,$setting);
			$this->redirect(site_url('admin/basicseo?type='.$type), lang('operate_success','admin'));
			return;
		}
		$this->setting = $setting;
		$this->output('global/basicseo');
	}

	public function basictime(){
		$this->timezones = lang('time_zone_list','admin');
		$this->output('global/basictime');
	}

	public function basicupload(){
		$api = load_api('setting');
		$setting = $api->getSetting('upload');
		$act=$this->param('act');
		if($act=='save'){
			$setting['allow_upload_size'] = $this->param('allow_upload_size','2048000');
			$setting['allow_max_num'] = $this->param('allow_max_num','10');
			$setting['allow_upload_type'] = $this->param('allow_upload_type','jpg|png|gif');
			$setting['upload_image_size_w'] = $this->param('upload_image_size_w','2048');
			$setting['upload_image_size_h'] = $this->param('upload_image_size_h','2048');
			$setting['fetch_image_size_w'] = $this->param('fetch_image_size_w','2048');
			$setting['fetch_image_size_h'] = $this->param('fetch_image_size_h','2048');
			$setting['wftwidth'] = $this->param('wftwidth','220');
			$setting['largewidth'] = $this->param('largewidth','600');
			$setting['squarewidth'] = $this->param('squarewidth','200');
			$setting['delete_source'] = $this->param('delete_source','0');

			$extension_whitelist = explode('|', $setting['allow_upload_type']);
			$exts = '';
			$exts_des = '';
			foreach ($extension_whitelist as $ext){
				$exts .= '*.'.$ext.';';
				$exts_des .= strtoupper($ext).' Files; ';
			}

			$setting['allow_upload_type_swf'] = $exts;
			$setting['allow_upload_type_swf_desc'] = $exts_des;

			$api->updateSetting('upload',$setting);
			$this->redirect(site_url('admin/basicupload'), lang('operate_success','admin'));
			return;
		}
		$this->setting = $setting;
		$this->output('global/basicupload');
	}

	public function basicsecode(){
		$api = load_api('setting');
		$setting = $api->getSetting('vcode');
		$act=$this->param('act');
		if($act=='save'){
			$setting['register'] = $this->param('register','0');
			$setting['login'] = $this->param('login','0');

			$api->updateSetting('vcode',$setting);
			$this->redirect(site_url('admin/basicsecode'), lang('operate_success','admin'));
			return;
		}
		$this->setting = $setting;
		$this->output('global/basicsecode');
	}

	public function basicshare(){
		$api = load_api('setting');
		$setting = $api->getSetting('share');
		$act=$this->param('act');
		if($act=='save'){
			$postvar = array('verify'=>'0','tagnum'=>'5','title_range_s'=>'2','title_range_l'=>'100',
					'content_range_s'=>'0','content_range_l'=>'10000','comment_range_s'=>'2','comment_range_l'=>'140',
					'album_range_s'=>'2','album_range_l'=>'20','domainwhitelist'=>'');
			foreach ($postvar as $key=>$default){
				$setting[$key] = $this->param($key,$default);
			}
			if(isset($setting['domainwhitelist'])) {
				$setting['domainwhitelist'] = trim(preg_replace("/(\s*(\r\n|\n\r|\n|\r)\s*)/", "\r\n", $setting['domainwhitelist']));
			}

			$api->updateSetting('share',$setting);
			$this->redirect(site_url('admin/basicshare'), lang('operate_success','admin'));
			return;
		}
		$this->setting = $setting;
		$this->output('global/basicshare');
	}

	public function basicemail(){
		$api = load_api('setting');
		$settingkey = 'email';
		$setting = $api->getSetting($settingkey);
		$this->act = $act=$this->param('act');
		if($act=='save'){
			$postvar = array('protocol'=>'mail','from'=>'NAN','sender'=>'NAN','smtp_host'=>'0','smtp_user'=>'','smtp_pass'=>'','smtp_port'=>'25');
			foreach ($postvar as $key=>$default){
				$setting[$key] = $this->param($key,$default);
			}
			$api->updateSetting($settingkey,$setting);
			$this->redirect(site_url('admin/basicemail'), lang('operate_success','admin'));
			return;
		}else if($act=='test'){
			$this->output('global/basicemailtest');
			return;
		}else if($act=='send'){
			$data['email']=$this->cuser['email'];
			$data['password']=$this->cuser['password'];
			$data['subject']=$this->param('subject');
			$data['to_email']=$this->param('to');
			$data['message']=$this->param('message');
			load_api('email')->adminsendtest($data);
			$this->redirect(site_url('admin/basicemail'), lang('operate_success','admin'));
			return;
		}
		$this->setting = $setting;
		$this->output('global/basicemail');
	}

	public function basicother(){
		$api = load_api('setting');
		$setting = $api->getSetting('global');
		$act=$this->param('act');
		if($act=='save'){
			$setting['price'] = $this->param('price','0');
			$setting['priceunit'] = $this->param('priceunit',lang('basic_other_priceunit_default','admin'));
			$setting['priceunitname'] = $this->param('priceunitname',lang('basic_other_priceunitname_default','admin'));

			$setting['show_coloridx'] = $this->param('show_coloridx','1');
			$setting['show_price_range'] = $this->param('show_price_range','0');
			
			$setting['price_range_1_label'] = $this->param('price_range_1_label','0-500');
			$setting['price_range_1_s'] = $this->param('price_range_1_s','0');
			$setting['price_range_1_l'] = $this->param('price_range_1_l','500');

			$setting['price_range_2_label'] = $this->param('price_range_2_label','500-1000');
			$setting['price_range_2_s'] = $this->param('price_range_2_s','500');
			$setting['price_range_2_l'] = $this->param('price_range_2_l','1000');

			$setting['price_range_3_label'] = $this->param('price_range_3_label','1000-9999');
			$setting['price_range_3_s'] = $this->param('price_range_3_s','1000');
			$setting['price_range_3_l'] = $this->param('price_range_3_l','9999');
			
			$api->updateSetting('global',$setting);
			$this->redirect(site_url('admin/basicother'), lang('operate_success','admin'));
			return;
		}
		$this->setting = $setting;
		$this->output('global/basicother');
	}

	public function layoutui(){
		$type = $this->param('type');
		$api = load_api('setting');
		$settingkey = ($type=='default')?'global':'layout'.$type;
		$setting = $api->getSetting($settingkey);
		$this->type = $type;
		$this->setting = $setting;
		$act=$this->param('act');
		if($type=='default'){
			if($act=='save'){
				$postvar = array('uidefault_login'=>'1','counter'=>array('click'),'store_open'=>'1','star_open'=>'1',);
				foreach ($postvar as $key=>$default){
					$setting[$key] = $this->param($key,$default);
				}
				$api->updateSetting($settingkey,$setting);
				$this->redirect(site_url('admin/layoutui?type=default'), lang('operate_success','admin'));
				return;
			}
			$this->setting['counter']=$this->setting['counter']?$this->setting['counter']:array('click');
			$this->output('layout/layoutui-default');
		}elseif($type=='album'){
			if($act=='save'){
				$postvar = array('uialbum_numperpage'=>'20','uialbum_minnum'=>'1','uialbum_layout'=>'4','uialbum_animated'=>'0','uialbum_auto'=>'1','uialbum_numbershowpage'=>'0');
				foreach ($postvar as $key=>$default){
					$setting[$key] = $this->param($key,$default);
				}
				$api->updateSetting($settingkey,$setting);
				load_api('album')->clearHotestAlbumCache();
				$this->redirect(site_url('admin/layoutui?type=album'), lang('operate_success','admin'));
				return;
			}
			$this->output('layout/layoutui-album');
		}elseif($type=='detail'){
			if($act=='save'){
				$postvar = array('uidetail_album'=>'1','uidetail_samefrom'=>'1','uidetail_recentview'=>'1','uidetail_guess'=>'1','uidetail_layout'=>'plain','uidetail_ads'=>'1','uidetail_comment_pagenum'=>'5');
				foreach ($postvar as $key=>$default){
					$setting[$key] = $this->param($key,$default);
				}
				$api->updateSetting($settingkey,$setting);
				$this->redirect(site_url('admin/layoutui?type=detail'), lang('operate_success','admin'));
				return;
			}
			$this->output('layout/layoutui-detail');
		}elseif($type=='home'){
			if($act=='save'){
				$postvar = array('uihome_hotshare_cachetime'=>'7','uihome_album'=>'1','uihome_album_num'=>'4','uihome_album_sharenum'=>'1','uihome_albumorder'=>'likes','uihome_user'=>'1','uihome_user_num'=>'4','uihome_category'=>'1','uihome_ads'=>'0');
				foreach ($postvar as $key=>$default){
					$setting[$key] = $this->param($key,$default);
				}
				$api->updateSetting($settingkey,$setting);
				$this->redirect(site_url('admin/layoutui?type=home'), lang('operate_success','admin'));
				return;
			}
			$this->output('layout/layoutui-home');
		}elseif($type=='pin'){
			if($act=='save'){
				$postvar = array('uipin_numperpage'=>'20','uipin_numcomment'=>'5','uipin_columnwidth'=>'235','uipin_showforward'=>'1','uipin_showarticle'=>'1','uipin_auto'=>'1','uipin_multi'=>'1','uipin_animated'=>'0','uipin_ads'=>'1','uipin_layout'=>'wf','uipin_timesort'=>'create_time','uipin_numbershowpage'=>'0');
				foreach ($postvar as $key=>$default){
					$setting[$key] = $this->param($key,$default);
				}
				$api->updateSetting($settingkey,$setting);
				$this->redirect(site_url('admin/layoutui?type=pin'), lang('operate_success','admin'));
				return;
			}
			$this->output('layout/layoutui-pin');
		}
	}

	public function layoutcolor(){
		$colors=array('red'=>'#E82835','purple'=>'#ff00ff','yellow'=>'#ffff00','blue'=>'#008ED0','green'=>'#77cc33','black'=>'#000000','gray'=>'#cccccc');
		$api = load_api('setting');
		$settingkey = 'colorindex';
		$setting = $api->getSetting($settingkey);
		$this->setting = $setting;
		$act=$this->param('act');
		if($act=='save'){
			foreach ($colors as $key=>$default){
				$setting[$key] = $this->param($key,$default);
			}
			$api->updateSetting($settingkey,$setting);
			$this->redirect(site_url('admin/layoutcolor'), lang('operate_success','admin'));
			return;
		}
		$this->output('layout/layoutcolor');
	}

	public function layoutusertheme(){
		$api = load_api('setting');
		$settingkey = 'usertheme';
		$setting = $api->getSetting($settingkey);
		$this->setting = $setting;
		$act=$this->param('act');
		if($act=='load'){
			$params = array('themename');
			if($theme = $this->param('themename')){
				$setting[$theme]['name'] = $theme;
				$setting[$theme]['css'] = 'assets/themes/'.$theme.'/style.css';
				$setting[$theme]['thumb'] = 'assets/themes/'.$theme.'/skin.png';
			}
			$api->updateSetting($settingkey,$setting);
			$this->redirect(site_url('admin/layoutusertheme'), lang('operate_success','admin'));
			return;
		}elseif($act=='delete'){
			$params = array('themename');
			if($theme = $this->param('themename')){
				if($setting[$theme]) unset($setting[$theme]);
			}
			$api->updateSetting($settingkey,$setting);
			$this->redirect(site_url('admin/layoutusertheme'), lang('operate_success','admin'));
			return;
		}else{
			load_helper('file');
			$locals_dir = BASEPATH.'assets/themes/';
			$file_list = get_dir_file_info($locals_dir);
			$dir = array();
			foreach ($file_list as $d) {
				$style['themename'] = $d['name'];
				$style['thumb'] = base_url().'assets/themes/'.$d['name'].'/skin.png';
				if(isset($setting[$d['name']])) $style['loaded'] = true; else $style['loaded'] = false;
				$themes[] = $style;
			}
			$this->themes = $themes;
		}
		$this->output('layout/layoutusertheme');
	}

	public function layoutstyle(){
		$cssvar = array('themecolor'=>'#f89406','bordercolor'=>'#DDD','smallFont'=>'13px','mediumFont'=>'14px','largeFont'=>'15px','gray'=>'#999',
				'blue'=>'#049cdb','green'=>'#46a546','red'=>'#9d261d','yellow'=>'#ffc40d',
				'orange'=>'#f89406','pink'=>'#c3325f','purple'=>'#7a43b6','puzzColor'=>'#EA4C89','bodyBackground'=>'#fff','textColor'=>'@grayDark','linkColor'=>'@puzzColor',
				'contentBackPath'=>'@{imagePath}/bgnoise.gif','contentBackGround'=>'#F0F0F0 url(@{contentBackPath}) repeat -70% 0','contentInnerBackGround'=>'url(@{imagePath}/big-fade.png) repeat-x -70% 0'
				,'boldFontFamily'=>'\'Microsoft YaHei\'',
				'baseFontFamily'=>'tahoma,\'Helvetica Neue\', Arial, \'Liberation Sans\', FreeSans, sans-serif','baseLineHeight'=>'18px',
				'inputBackground'=>'#fff','inputBorder'=>'#ccc','dropdownBackground'=>'@white','dropdownBorder'=>'rgba(0,0,0,.1)',
				'dropdownLinkColor'=>'@gray','dropdownLinkColorHover'=>'#fff','dropdownLinkBackgroundHover'=>'@puzzColor',
				'dropdownDivider'=>'lighten(@gray, 25%)',
				'navbarHeight'=>'51px','navbarBackground'=>'darken(@puzzColor, 15%)','navbarBackgroundHighlight'=>'darken(@puzzColor, 20%)','navbarText'=>'lighten(@puzzColor, 50%)',
				'navbarLinkColor'=>'lighten(@puzzColor, 60%)','navbarLinkColorHover'=>'#fff','navtxtshadow'=>'0 -1px 0 rgba(0,0,0,.25)','navbarSearchBackground'=>'lighten(@navbarBackground, 15%)'
		);
		$api = load_api('setting');
		$styles = $api->getStyleSetting();
		$act=$this->param('act');
		if($act=='setting'){
			$settings = $api->getGlobalSetting();
			$colorname=$this->param('ccolor');
			$themename=$this->param('ctheme');
			if($themename!=$settings['style']||$colorname!=$settings['color']){
				$settings['style'] = $themename?$themename:'puzzing';
				$settings['color'] = $colorname?$colorname:'default';
				$api->updateSetting('global',$settings);
				$this->template->updateless('boot',$themename,$colorname);
			}
			$this->redirect(site_url('admin/layoutstyle'), lang('operate_success','admin'));
			return;
		}elseif($act=='addcolor'){
			$colorname=$this->param('colorname');
			$themename=$this->param('themename');
			if($styles[$themename][$colorname]){
				$this->ajax_failed_response('themecolor_existed');
				return;
			}else{
				$styles[$themename][$colorname] = $cssvar;
				$api->updateSetting('ui_styles',$styles);
				$this->ajax_success_response('',lang('operate_success','admin'));
				return;
			}
		}elseif($act=='getcolors'){
			$themename=$this->param('themename','puzzing');
			$colors[] = 'default';
			if($styles[$themename]){
				foreach($styles[$themename] as $key=>$color){
					$colors[] = $key;
				}
			}
			$this->ajax_success_response($colors);
			return;
		}elseif($act=='getcolor'){
			$themename=$this->param('themename');
			$colorname=$this->param('colorname');
			if($styles[$themename][$colorname]){
				$color = $styles[$themename][$colorname];
				foreach ($cssvar as $key=>$val){
					if(!$color[$key]){
						$color[$key] = $val;
					}
				}
				$this->color = $color;
			}else{
				$this->color = $cssvar;
			}
			$this->themename = $themename;
			$this->colorname = $colorname;
			$this->output('layout/layoutstyle-edit');
			return;
		}elseif($act=='editcolor'){
			$themename=$this->param('themename');
			$colorname=$this->param('colorname');
			foreach ($cssvar as $key=>$val){
				if($v = $this->param($key)){
					$cssvar[$key] = $v;
				}
			}
			$styles[$themename][$colorname] = $cssvar;
			$api->updateSetting('ui_styles',$styles);
			$this->template->updateless('boot',$themename,$colorname,1);
			$this->redirect(site_url('admin/layoutstyle'), lang('operate_success','admin'));
			return;
		}elseif($act=='deletecolor'){
			$themename=$this->param('themename');
			$colorname=$this->param('colorname');
			if($styles[$themename][$colorname]){
				unset($styles[$themename][$colorname]);
				$api->updateSetting('ui_styles',$styles);
			}
			$this->redirect(site_url('admin/layoutstyle'), lang('operate_success','admin'));
			return;
		}else{
			load_helper('file');
			$locals_dir = BASEPATH.'themes/';
			$file_list = get_dir_file_info($locals_dir);
			$dir = array();
			$existstyles = array();
			//$existstyles['puzzing']['default'] = 1;
			foreach ($file_list as $d) {
				if(!in_array($d['name'], array('csstpl','admin','install','upgrade'))){
					$style['themename'] = $d['name'];
					$colors = $styles[$d['name']];
					$colors['default'] = 'default';

					foreach($colors as $key=>$color){
						$style['themecolor'] = $key;
						$colorStyles[] = $style;
						$existstyles[$style['themename']][$key] = 1;
					}
					$themes[] = $style;
				}
			}
			$settings = $api->getGlobalSetting();
			$settings['existedstyles'] = $existstyles;
			if($styles[$settings['style']]){
				$colors['default'] = array('name'=>'default','themecolor'=>'#000');
				foreach($styles[$settings['style']] as $key=>$color){
					$colors[$key]['name'] = $key;
					$colors[$key]['themecolor'] = $color['themecolor']?$color['themecolor']:'#fff';
				}
				$settings['colors'] = $colors;
			}
			$api->updateSetting('global',$settings);
			$this->themes = $themes;
			$this->colorStyles = $colorStyles;
			$this->ctheme = $settings['style'];
			$this->ccolor = $settings['color'];
		}
		$this->output('layout/layoutstyle');
	}

	public function layoutsmiles(){
		$act=$this->param('act');
		$smileid = $this->param("smileid");
		$page = $this->param("page",1);
		$api = load_api('setting');
		if($smileid){
			$smile = $api->getSmileByid($smileid);
		}
		if($act=='delete'&&$smile){
			$smile = $api->deleteSmileByid($smileid);
			$this->redirect(site_url('admin/layoutsmiles'),lang('200_deletesuccess','tip'));
			return;
		}else if($act=='edit'&&$smile){
			if($data['code'] = $this->param('code')){
				$data['displayorder'] = $this->param('displayorder');
				$data['url'] = $this->param('url');
				$api->updateSmileByid($smileid,$data);
				$this->redirect(site_url('admin/layoutsmiles'),lang('200_updatesuccess','tip'));
				return;
			}else{
				$this->smile = $smile;
				$this->output('layout/layoutsmiles-edit');
				return;
			}
		}else if($act=='add'){
			$data['code'] = $this->param('code');
			$data['displayorder'] = $this->param('displayorder');
			$data['url'] = $this->param('url');
			$data['typeid'] = 1;
			$api->addsmile($data);
			$this->redirect(site_url('admin/layoutsmiles'),lang('200_updatesuccess','tip'));
			return;
		}else{
			$this->smiles = $api->getSmiles($page,PAGESIZE);
			$pager = & load_class('Pager', 'core');
			$this->pages = $pager->createPages('admin/layoutsmiles',array('page'=>$page));
			$this->output('layout/layoutsmiles');
			return;
		}
	}

	public function sharebutton(){
		$act=$this->param('act');
		$key = $this->param('key');
		$settingapi = load_api('setting');
		$settingkey = 'sharebutton';
		$sharebuttons = $settingapi->getSetting($settingkey);
		if($act=='delete'){
			if($sharebuttons[$key]){
				unset($sharebuttons[$key]);
				$settingapi->updateSetting($settingkey,$sharebuttons);
			}
			$this->redirect(site_url('admin/sharebutton'), lang('operate_success','admin'));
			return;
		}else if($act=='edit'&&$key){
			if($name = $this->param('name')){
				if($sharebuttons[$key]){
					$sharebuttons[$key]['name'] = $this->param('name');
					$sharebuttons[$key]['link'] = $this->param('link','',false);
					$sharebuttons[$key]['width'] = $this->param('width');
					$sharebuttons[$key]['height'] = $this->param('height');
					$sharebuttons[$key]['open'] = $this->param('open');
					$settingapi->updateSetting($settingkey,$sharebuttons);
				}
				$this->redirect(site_url('admin/sharebutton'),lang('200_updatesuccess','tip'));
				return;
			}else{
				$this->key = $key;
				$sharebuttons[$key]['link'] = $sharebuttons[$key]['link'];
				$this->sharebutton = $sharebuttons[$key];
				$this->output('operation/sharebutton-edit');
				return;
			}
		}else if($act=='add'){
			$sharebuttons[$key]['name'] = $this->param('name');
			$sharebuttons[$key]['link'] = $this->param('link','',false);
			$sharebuttons[$key]['displayorder'] = $this->param('displayorder');
			$sharebuttons[$key]['width'] = $this->param('width');
			$sharebuttons[$key]['height'] = $this->param('height');
			$sharebuttons[$key]['open'] = $this->param('open');
			$settingapi->updateSetting($settingkey,$sharebuttons);
			$this->redirect(site_url('admin/sharebutton'),lang('200_updatesuccess','tip'));
			return;
		}else{
			$this->sharebuttons = $sharebuttons;
			$this->output('operation/sharebutton');
			return;
		}
	}

	public function socialapi(){
		$act=$this->param('act');
		$key = $this->param('key');
		$settingapi = load_api('setting');
		$settingkey = 'socialapi';
		$socialapis = $settingapi->getSetting($settingkey);
		if($act=='delete'){
			if($socialapis[$key]){
				unset($socialapis[$key]);
				$settingapi->updateSetting($settingkey,$socialapis);
			}
			$this->redirect(site_url('admin/socialapi'), lang('operate_success','admin'));
			return;
		}else if($act=='edit'&&$key){
			if($name = $this->param('name')){
				if($socialapis[$key]){
					$postvar = array('key'=>'','name'=>'','appkey'=>'','appsecret'=>'','callback'=>'','unionid'=>'','open'=>'1');
					foreach ($postvar as $k=>$default){
						$socialapis[$key][$k] = $this->param($k,$default,false);
					}
					$settingapi->updateSetting($settingkey,$socialapis);
				}
				$this->redirect(site_url('admin/socialapi'),lang('200_updatesuccess','tip'));
				return;
			}else{
				$this->key = $key;
				$this->socialapi = $socialapis[$key];
				$this->output('operation/socialapi-edit');
				return;
			}
		}else if($act=='add'){
			$postvar = array('key'=>'','name'=>'','appkey'=>'','appsecret'=>'','callback'=>'','unionid'=>'','open'=>'1');
			foreach ($postvar as $k=>$default){
				$socialapis[$key][$k] = $this->param($k,$default,false);
			}
			$settingapi->updateSetting($settingkey,$socialapis);
			$this->redirect(site_url('admin/socialapi'),lang('200_updatesuccess','tip'));
			return;
		}else{
			$this->socialapis = $socialapis;
			$this->output('operation/socialapi');
			return;
		}
	}

	public function contentcategory(){
		$act=$this->param('act');
		$catid = $this->param("catid");
		$page = $this->param("page",1);
		$api = load_api('category');
		if($catid){
			$category = $api->getCategoryByid($catid);
		}
		if($act=='delete'&&$category){
			$api->deleteCategoryByid($catid);
			$this->redirect(site_url('admin/contentcategory'),lang('200_deletesuccess','tip'));
			return;
		}else if($act=='edit'&&$category){
			if($data['category_name_cn'] = $this->param('category_name_cn')){
				$categorytmp = $api->getCategoryByENName($this->param('category_name_en'));
				if($categorytmp&&$categorytmp['category_id']!=$catid){
					$this->redirect(site_url('admin/contentcategory'),lang('500_category_enname_exist','tip'));
					return;
				}
				$data['display_order'] = $this->param('display_order');
				$data['category_name_en'] = $this->param('category_name_en');
				$data['parent_id'] = $this->param('parent_id');
				$data['parent_name'] = $this->param('parent_name');
				$data['is_open'] = $this->param('is_open');
				$data['is_home'] = $this->param('is_home');
				$data['category_hot_words'] = $this->param('category_hot_words');
				$data['description'] = $this->param('description');
				$api->updateCategoryByid($catid,$data);
				$this->redirect(site_url('admin/contentcategory'),lang('200_updatesuccess','tip'));
				return;
			}else{
				$this->rootcategories = $api->getRootCategories();
				$this->category = $category;
				$this->output('content/category-edit');
				return;
			}
		}else if($act=='add'){
			if($api->getCategoryByENName($this->param('category_name_en'))){
				$this->redirect(site_url('admin/contentcategory'),lang('500_category_enname_exist','tip'));
				return;
			}
			$data['category_name_cn'] = $this->param('category_name_cn');
			$data['display_order'] = $this->param('display_order');
			$data['category_name_en'] = $this->param('category_name_en');
			$data['parent_id'] = $this->param('parent_id');
			$data['parent_name'] = $this->param('parent_name');
			$data['is_open'] = $this->param('is_open');
			$data['is_home'] = $this->param('is_home');
			$data['category_hot_words'] = $this->param('category_hot_words');
			$data['description'] = $this->param('description');
			$api->addCategory($data);
			$this->redirect(site_url('admin/contentcategory'),lang('200_updatesuccess','tip'));
			return;
		}elseif($act=='upload'){
			$attachmentapi = load_api('attachment');
			$settings =  $this->settings;
			$allowedExtensions = array('jpg','jpeg','gif','png');
			$sizeLimit = 2 * 1024 * 1024;
			$temp_dir = BASEPATH.'data/attachments/category/';
			(!is_dir($temp_dir))&&@mkdir($temp_dir,0777,true);
			$result = $attachmentapi->simpleUpload($temp_dir,true,$allowedExtensions,$sizeLimit);

			if($result['success']){
				$filepath = $temp_dir.$result['data']['filename'].'.'.$result['data']['ext'];
				$newfilepath = $temp_dir.$catid.'_cat.jpg';
				$imagelib = &load_class('ImageLib');
				$imagelib->create_thumb($filepath, false, 100,100,$newfilepath);
				file_exists($filepath) && unlink($filepath);
			}
			$this->ajax_success_response('');
			return;
		}else{
			$this->categories = $api->getCategories($page,PAGESIZE);
			$this->rootcategories = $api->getRootCategories();
			$this->deepcategories = $api->getCategoryDeepTree();
			$pager = & load_class('Pager', 'core');
			$this->pages = $pager->createPages('admin/contentcategory',array('page'=>$page));
			$this->output('content/category');
			return;
		}
	}

	public function contentshare(){
		$act=$this->param('act');
		$shareid = $this->param("shareid");
		$page = $this->param("page",1);
		$api = load_api('share');
		if($shareid){
			$share = $api->getShareById($tagid);
		}
		if($this->param('catid')){
			$this->catid = $conditions['category_id'] = $this->param('catid');
		}

		if($this->param('keyword')){
			$this->keyword = $conditions['likekeyword'] = $this->param('keyword');
		}

		$this->is_show = $conditions['is_show'] = $this->param('is_show','0');
		if($act=='batchDelete'){
			$ids = $this->param("ids");
			$ids = explode(',', $ids);
			foreach ($ids as $id){
				$api->deleteShareById($id);
			}
			$conditions['page'] = $page;
			$this->ajax_success_response(array('url'=>site_url_param('admin/contentshare',$conditions)),lang('200_deletesuccess','tip'));
			return;
		}if($act=='delete'){
			$id = $this->param("id");
			$api->deleteShareById($id);
			$conditions['page'] = $page;
			$this->redirect(site_url_param('admin/contentshare',$conditions),lang('200_deletesuccess','tip'));
			return;
		}else if($act=='batchVerify'){
			$ids = $this->param("ids");
			$ids = explode(',', $ids);
			foreach ($ids as $id){
				$sa = $api->getShareById($id);
				load_db('share/item')->update(array('item_id'=>$sa['item_id']),array('is_show'=>1));
			}
			$this->ajax_success_response(array('url'=>site_url_param('admin/contentshare',$conditions)),lang('200_updatesuccess','tip'));
			return;
		}else{
			$shareapi = load_api('share');
			$shares = $shareapi->search($conditions,$page,PAGESIZE," ptx_share.create_time DESC ");
			$this->shares = $shareapi->prepareShares($shares);
			$conditions['page'] = $page;
			$pager = & load_class('Pager', 'core');
			$conditions['keyword'] = $conditions['likekeyword'];
			unset($conditions['likekeyword']);
			$this->pages = $pager->createPages('admin/contentshare',$conditions);
			$conditions['act']='batchDelete';
			$this->delurl = site_url_param('admin/contentshare',$conditions);
			$conditions['act']='batchVerify';
			$this->verurl = site_url_param('admin/contentshare',$conditions);
			$this->output('content/shares');
			return;
		}
	}

	public function contenttag(){
		$act=$this->param('act');
		$tagid = $this->param("tagid");
		$page = $this->param("page",1);
		$api = load_api('tag');
		if($tagid){
			$tag = $api->getTagByid($tagid);
		}
		if($act=='delete'&&$tag){
			$api->deleteTagByid($tagid);
			$this->redirect(site_url('admin/contenttag'),lang('200_deletesuccess','tip'));
			return;
		}else if($act=='edit'&&$tag){
			if($data['tag_group_name_cn'] = $this->param('tag_group_name_cn')){
				$data['category_id'] = $this->param('category_id');
				$data['tag_group_name_en'] = $this->param('tag_group_name_en');
				$data['display_order'] = $this->param('display_order');
				$data['tags'] = $this->param('tags');
				$api->updateTagByid($tagid,$data);
				$this->redirect(site_url('admin/contenttag'),lang('200_updatesuccess','tip'));
				return;
			}else{
				$this->categories = load_api('category')->getLastLevelCategories();
				$this->tag = $tag;
				$this->output('content/tag-edit');
				return;
			}
		}else if($act=='add'){
			$data['tag_group_name_cn'] = $this->param('tag_group_name_cn');
			$data['category_id'] = $this->param('category_id');
			$data['tag_group_name_en'] = $this->param('tag_group_name_en');
			$data['display_order'] = $this->param('display_order');
			$data['tags'] = $this->param('tags');
			$api->addTag($data);
			$this->redirect(site_url('admin/contenttag'),lang('200_updatesuccess','tip'));
			return;
		}else{
			$this->tags = $api->getTags($page,PAGESIZE);
			$this->categories = load_api('category')->getLastLevelCategories();
			$pager = & load_class('Pager', 'core');
			$this->pages = $pager->createPages('admin/contenttag',array('page'=>$page));
			$this->output('content/tag');
			return;
		}
	}

	public function contenttopic(){
		$act=$this->param('act');
		$topicid = $this->param("topicid");
		$page = $this->param("page",1);
		$db = load_db("topic");
		if($topicid){
			$topic = $db->find_one(array('topic_id'=>$topicid));
		}
		if($act=='delete'&&$topic){
			load_api('topic')->delete($topicid);
			$this->redirect(site_url('admin/contenttopic'),lang('200_deletesuccess','tip'));
			return;
		}else if($act=='edit'&&$topic){
			if($data['topic_title'] = $this->param('topic_title')){
				$params = array('topic_title','topic_desc','category_id','keyword');
				foreach ($params as $key){
					$data[$key] = $this->param($key);
				}
				if($data['keyword']){
					$data['keyword_search'] = encodekeywords(explode(',', $data['keyword']));
				}
				$db->update(array('topic_id'=>$topicid),$data);
				$this->redirect(site_url('admin/contenttopic'),lang('200_updatesuccess','tip'));
				return;
			}else{
				$this->topic = $topic;
				$this->output('content/contenttopic-edit');
				return;
			}
		}else{
			$this->topics = $db->search(null,$page,PAGESIZE);;
			$pager = & load_class('Pager', 'core');
			$this->pages = $pager->createPages('admin/contenttopic',array('page'=>$page));
			$this->output('content/contenttopic');
			return;
		}
	}

	public function contentgroup(){
		$act=$this->param('act');
		$groupid = $this->param("groupid");
		$page = $this->param("page",1);
		$db = load_db("group");
		if($groupid){
			$group = $db->find_one(array('group_id'=>$groupid));
		}
		if($act=='delete'&&$group){
			load_db('group')->delete(array('group_id'=>$groupid));
			load_db("group/ugroup")->delete(array('group_id'=>$groupid));
			$this->redirect(site_url('admin/contentgroup'),lang('200_deletesuccess','tip'));
			return;
		}else if($act=='edit'&&$group){
			if($data['group_title'] = $this->param('group_title')){
				$params = array('group_title','group_desc','category_id','keyword');
				foreach ($params as $key){
					$data[$key] = $this->param($key);
				}
				if($data['keyword']){
					$data['keyword_search'] = encodekeywords(explode(',', $data['keyword']));
				}
				$db->update(array('group_id'=>$groupid),$data);
				$this->redirect(site_url('admin/contentgroup'),lang('200_updatesuccess','tip'));
				return;
			}else{
				$this->group = $group;
				$this->output('content/contentgroup-edit');
				return;
			}
		}else{
			$this->groups = $db->search(null,$page,PAGESIZE);;
			$pager = & load_class('Pager', 'core');
			$this->pages = $pager->createPages('admin/contentgroup',array('page'=>$page));
			$this->output('content/contentgroup');
			return;
		}
	}

	public function contentcensor(){
		$act=$this->param('act');
		$censorid = $this->param("censorid");
		$page = $this->param("page",1);
		$api = load_api('censor');
		if($censorid){
			$censor = $api->getcensorbyid($censorid);
		}
		if($act=='delete'&&$censor){
			$api->deleteCensorByid($censorid);
			$this->redirect(site_url('admin/contentcensor'),lang('200_deletesuccess','tip'));
			return;
		}else if($act=='edit'&&$censor){
			if($data['find'] = $this->param('find')){
				$data['replacement'] = $this->param('replacement');
				if($data['replacement']=='{REPLACE}'){
					$data['replacement'] = $this->param('replacementtxt');
				}
				$data['extra'] = $this->param('extra');
				$data['type'] = $this->param('type');
				$api->updateCensorByid($censorid,$data);
				$this->redirect(site_url('admin/contentcensor'),lang('200_updatesuccess','tip'));
				return;
			}else{
				$this->censortypes = $api->getcensortypes($page,1000);
				$this->censor = $censor;
				$this->output('content/contentcensor-edit');
				return;
			}
		}else if($act=='add'){
			$data['find'] = $this->param('find');
			$data['admin'] = $this->cuser['nickname'];
			$data['replacement'] = $this->param('replacement');
			if($data['replacement']=='{REPLACE}'){
				$data['replacement'] = $this->param('replacementtxt');
			}
			$data['extra'] = $this->param('extra');
			$data['type'] = $this->param('type');
			$api->addcensor($data);
			$this->redirect(site_url('admin/contentcensor'),lang('200_updatesuccess','tip'));
			return;
		}else{
			$this->censors = $api->getcensorwords($page,PAGESIZE);
			$this->censortypes = $api->getcensortypes($page,1000);
			$pager = & load_class('Pager', 'core');
			$this->pages = $pager->createPages('admin/contentcensor',array('page'=>$page));
			$this->output('content/contentcensor');
			return;
		}
	}

	public function contentcensorbatch(){
		$act=$this->param('act');
		$api = load_api('censor');
		if($act=='add'){
			$addcensors = $this->param('addcensors');
			$opt = $this->param('opt');
			$type = $this->param('type');


			$oldwords = array();
			if($opt == 2) {
				$api->clearallcensor();
			} else {
				foreach($api->getallcensorwords() as $censor) {
					$oldwords[md5($censor['find'])] = $censor['admin'];
				}
			}
			$typesearch = "\[type\:(.+?)\](.+?)\[\/type\]";
			preg_match_all("/($typesearch)/is", $addcensors, $wordmatch);
			$wordmatch[3][] = preg_replace("/($typesearch)/is", '', $addcensors);
			$updatecount = $newcount = $ignorecount = 0;
			foreach($wordmatch[3] AS $key => $val) {
				$word_type = 1;
				if($wordmatch[2][$key] && !$wordtype_used[$key]) {
					$row = $api->getcensortypebytypename($wordmatch[2][$key]);
					if($row) {
						$word_type = $row['id'];
					} else {
						$word_type['typename'] = $wordmatch[2][$key];
						$word_type['id'] = $api->addcensortype($word_type);
					}
					$wordtype_used[$key] = 1;
				}
				$word_type = $word_type ? $word_type : 1 ;
					
				$censorarray = explode("\n", $val);
				foreach($censorarray as $censor) {
					list($newfind, $newreplace) = array_map('trim', explode('=', $censor));
					$newreplace = $newreplace <> '' ? daddslashes(str_replace("\\\'", '\'', $newreplace), 1) : '**';
					if(strlen($newfind) < 3) {
						if($newfind != '') {
							$ignorecount ++;
						}
						continue;
					} elseif(isset($oldwords[md5($newfind)])) {
						if($opt && ($this->cuser['uid'] == 1 || $oldwords[md5($newfind)] == $this->cuser['nickname'])) {
							$updatecount ++;
							$api->updateCensorByFind($newfind, array(
									'replacement' => $newreplace,
									'type' => ($word_type ? $word_type : (intval($type) ? intval($type) : 1))
							));
						} else {
							$ignorecount ++;
						}
					} else {
						$newcount ++;
						$api->addcensor(array(
								'admin' => $this->cuser['nickname'],
								'find' => $newfind,
								'replacement' => $newreplace,
								'type' => ($word_type ? $word_type : (intval($type) ? intval($type) : 1))
						));
						$oldwords[md5($newfind)] = $this->cuser['nickname'];
					}
				}
					
			}


			$api->updatecensorcache();
			//cpmsg('censor_batch_add_succeed', "action=misc&operation=censor&anchor=import", 'succeed', array('newcount' => $newcount, 'updatecount' => $updatecount, 'ignorecount' => $ignorecount));
			$this->redirect(site_url('admin/contentcensor'),lang('200_updatesuccess','tip').' '.sprintf(lang('censor_batch_success','admin'),$newcount,$updatecount,$ignorecount), 5);
			return;
		}elseif($act=='export'){
			load_helper('download');
			$data='';
			foreach($api->getallcensortypes() as $result) {
				$result['used'] = 0;
				$word_type[$result['id']] = $result;
			}
			foreach($api->findAllOrderTypeFind() as $censor) {
				$censor['replacement'] = str_replace('*', '', $censor['replacement']) <> '' ? $censor['replacement'] : '';
				if($word_type[$censor['type']]['used'] == 0 && $word_type[$censor['type']]) {
					if($temp_type == 1) {
						$data .= "[/type]\n";
					}
					$data .= "\n[type:".$word_type[$censor['type']]['typename']."]\n";
					$temp_type = 1;
					$word_type[$censor['type']]['used'] = 1;
				}
				$data .= $censor['find'].($censor['replacement'] != '' ? '='.$censor['replacement'] : '')."\n";
			}
			if($temp_type == 1) {
				$data .= "[/type]\n";
				unset($temp_type);
			}
			force_download('CensorWords.txt',$data);
			return;
		}else{
			$this->censortypes = $api->getcensortypes($page,100);
			$this->output('content/contentcensorbatch');
			return;
		}
	}

	public function contentcensortype(){
		$act=$this->param('act');
		$id = $this->param("id");
		$page = $this->param("page",1);
		$api = load_api('censor');
		if($id){
			$censortype = $api->getcensortypebyid($id);
		}
		if($act=='delete'&&$censortype){
			$api->deleteCensortypeByid($id);
			$this->redirect(site_url('admin/contentcensortype'),lang('200_deletesuccess','tip'));
			return;
		}else if($act=='edit'&&$censortype){
			if($data['typename'] = $this->param('typename')){
				$api->updateCensortypeByid($id,$data);
				$this->redirect(site_url('admin/contentcensortype'),lang('200_updatesuccess','tip'));
				return;
			}else{
				$this->censortype = $censortype;
				$this->output('content/contentcensortype-edit');
				return;
			}
		}else if($act=='add'){
			$data['typename'] = $this->param('typename');
			$api->addcensortype($data);
			$this->redirect(site_url('admin/contentcensortype'),lang('200_updatesuccess','tip'));
			return;
		}else{
			$this->censortypes = $api->getcensortypes($page,PAGESIZE);
			$pager = & load_class('Pager', 'core');
			$this->pages = $pager->createPages('admin/contentcensortype',array('page'=>$page));
			$this->output('content/contentcensortype');
			return;
		}
	}

	public function banuser(){
		$uid = $this->param("uid");
		if($uid==$this->cuser['uid']){
			$this->ajax_failed_response(lang('500_cannot_bindself','tip'));
			return;
		}else if($uid===1){
			$this->ajax_failed_response(lang('500_cannot_bindcreator','tip'));
			return;
		}else{
			$userapi = load_api('user');
			$userapi->updateUserSystemGroupBP($uid);
			$shareapi = load_api('share');
			$shareapi->mvBannedUserPostToDeleted($uid);
			$this->ajax_success_response(null,lang('200_operatesuccess','tip'));
			return;
		}
	}

	public function userlist(){
		$act=$this->param('act');
		$uid = $this->param("uid");
		$page = $this->param("page",1);
		$api = load_api('user');
		if($uid){
			$user = $api->getUserWithGroupByid($uid);
		}
		if($act=='delete'&&$user){
			$api->deleteUserByid($uid);
			$this->redirect(site_url('admin/userlist'),lang('200_deletesuccess','tip'));
			return;
		}else if($act=='edit'&&$user){
			if($this->param('submit')){
				if($this->param("password")){
					$data['passwd'] = md5($this->param("password"));
				}
				$sysgid = $this->param("sysgid");
				$mbmgid = $this->param("mbmgid");
				$spegid = $this->param("spegid");
				$data['user_title'] = $this->param("user_title");
				$data['bio'] = $this->param("bio");
				$api->updateUserGroup($uid,$sysgid,$mbmgid,$spegid);
				$api->updateUserByid($uid,$data);
				$sysgroup = load_api('user/usergroup')->getGroupByid($sysgid,'system');
				if($user['system']['usergroup_key']=='banned_post'&&$sysgroup['usergroup_key']!='banned_post'){
					load_api('share')->unBannedUserPostFromDeleted($uid);
				}else if($sysgroup['usergroup_key']=='banned_post'){
					load_api('share')->mvBannedUserPostToDeleted($uid);
				}

				$this->redirect(site_url('admin/userlist'),lang('200_updatesuccess','tip'));
				return;
			}else{
				$gapi = load_api('user/usergroup');
				$this->systemGroups = $gapi->getSystemUserGroup();
				$this->specialGroups = $gapi->getSpecialUserGroup();
				$this->memberGroups = $gapi->getMemberUserGroup();
				$this->user = $user;
				$this->output('user/useredit');
				return;
			}
		}elseif($act=='search'){
			if($this->param("sysgid")){
				$this->sysgid = $condition['sysid'] = $this->param("sysgid");
			}
			if($this->param("mbmgid")){
				$this->mbmgid = $condition['memid'] = $this->param("mbmgid");
			}
			if($this->param("keyword")){
				$this->keyword = $condition['likekeyword'] = $this->param("keyword");
			}
			$this->users = $api->adminSearchUsers($condition,$page,PAGESIZE);
			$pager = & load_class('Pager', 'core');
			$condition['page'] = $page;
			$this->pages = $pager->createPages('admin/userlist',$condition);
			$gapi = load_api('user/usergroup');
			$this->systemGroups = $gapi->getSystemUserGroup();
			$this->specialGroups = $gapi->getSpecialUserGroup();
			$this->memberGroups = $gapi->getMemberUserGroup();
			$this->output('user/userlist');
			return;
		} else{
			$gapi = load_api('user/usergroup');
			$this->systemGroups = $gapi->getSystemUserGroup();
			$this->specialGroups = $gapi->getSpecialUserGroup();
			$this->memberGroups = $gapi->getMemberUserGroup();
			$this->users = $api->adminSearchUsers('',$page,PAGESIZE);
			$pager = & load_class('Pager', 'core');
			$this->pages = $pager->createPages('admin/userlist',array('page'=>$page));
			$this->output('user/userlist');
			return;
		}
	}

	function checkformulasyntax($formula, $operators, $tokens) {
		$var = implode('|', $tokens);
		$operator = implode('', $operators);

		$operator = str_replace(
				array('+', '-', '*', '/', '(', ')', '{', '}', '\''),
				array('\+', '\-', '\*', '\/', '\(', '\)', '\{', '\}', '\\\''),
				$operator
		);
		$str = preg_replace("/($var)/", "\$\\1", $formula);
		if(!empty($formula)) {
			if(!preg_match("/^([$operator\.\d\(\)]|(($var)([$operator\(\)]|$)+))+$/", $formula) || !is_null(eval($str.';'))){
				return false;
			}
		}
		return $str;
	}

	function checkformulacredits($formula) {
		return $this->checkformulasyntax(
				$formula,
				array('+', '-', '*', '/', ' '),
				array('ext_credits_[1-3]', 'total_followers', 'total_shares', 'total_likes')
		);
	}

	public function credit(){
		$this->type = $type=$this->param('type');
		$act=$this->param('act');
		$settingapi = load_api('setting');
		$settingkey = 'credit';
		$setting = $settingapi->getSetting($settingkey);
		$setting['ext_credits_1'] = ($setting['ext_credits_1'])?$setting['ext_credits_1']:'ext_credits_1';
		$setting['ext_credits_2'] = ($setting['ext_credits_2'])?$setting['ext_credits_2']:'ext_credits_2';
		$setting['ext_credits_3'] = ($setting['ext_credits_3'])?$setting['ext_credits_3']:'ext_credits_3';
		$this->setting = $setting;
		if($type=='setting'){
			if($act=='save'){
				$setting['credit_formula'] = $this->param('credit_formula');
				$setting['credit_formula_exe'] =$this->checkformulacredits($setting['credit_formula']);
				$setting['ext_credits_1'] = $this->param('ext_credits_1','ext_credits_1');
				$setting['ext_credits_2'] = $this->param('ext_credits_2','ext_credits_2');
				$setting['ext_credits_3'] = $this->param('ext_credits_3','ext_credits_3');
				$settingapi->updateSetting($settingkey,$setting);
				$this->redirect(site_url('admin/credit?type=setting'), lang('operate_success','admin'));
				return;
			}

			$this->output('user/creditsetting');
			return;
		}else if($type=='strategy'){
			if($act=='save'){
				$parms = array('cycletype'=>'everyday','rewardnum'=>'1','ext_credits_1'=>'0','ext_credits_2'=>'0','ext_credits_3'=>'0');
				foreach ($parms as $key=>$val){
					$data[$key]=$this->param($key,$val);
				}
				load_api('event/eventrule')->updateRuleByid($this->param('rid'),$data);
				$this->redirect(site_url('admin/credit?type=strategy'), lang('operate_success','admin'));
				return;
			}if($act=='edit'){
				$this->rule = load_api('event/eventrule')->getRuleByid($this->param('rid'));
				$this->output('user/creditstrategy-edit');
				return;
			}else{
				$this->rules = load_api('event/eventrule')->getRules();
				$this->output('user/creditstrategy');
			}
		}
	}

	public function usergroup(){
		$act=$this->param('act');
		$type=$this->param('type');
		$this->type = $type;
		$gid = $this->param("gid");
		$page = $this->param("page",1);
		$api = load_api('user/usergroup');
		if($gid){
			$group = $api->getGroupByid($gid,$type);
		}
		if($act=='delete'&&$group){
			$api->deleteGroupByid($gid);
			$this->redirect(site_url('admin/usergroup?type='.$type),lang('200_deletesuccess','tip'));
			return;
		}else if($act=='edit'&&$group){
			if($this->param('submit')){
				$data['usergroup_name'] = $this->param('group_name');
				$data['usergroup_key'] = $this->param('group_key');
				$data['color'] = $this->param('group_color');
				$data['usergroup_type'] = $type;
				if($type=='member'){
					$data['credits_lower'] = $this->param('credits_lower');
					$data['credits_higher'] = $this->param('credits_higher');
				}
				$api->updateGroup($gid,$data);
				$this->redirect(site_url('admin/usergroup?type='.$type),lang('200_updatesuccess','tip'));
				return;
			}else{
				$this->group = $group;
				$this->output('user/usergroup-edit');
				return;
			}
		}else if($act=='permission'&&$group){
			$permissions = array(
					'system'=>array('allowvisite'=>'100','allowmessage'=>'1','allowposturl'=>'0','allowpost'=>'1','postverify'=>'0','allowcomment'=>'1','allowupload'=>'1'
							,'allowat'=>'1','allowdownload'=>'1','ignorecensor'=>'0'),
					'member'=>array('allowurl'=>'0','allowposturl'=>'0','maxalbum'=>'10','maxfollow'=>'20','maxattachnum'=>'10','maxattachsize'=>'2048000','maxmessage'=>'20'
							,'allowvideo'=>'1','allowfetch'=>'1','allowfileext'=>'jpg|png|gif|zip'
							,'maxcrgroup'=>'0','maxcrtopic'=>'0'),
					'special'=>array()
			);


			if($this->param('submit')){
				foreach ($permissions[$type] as $key=>$df){
					$gp[$key] = $this->param($key,$df);
				}
				$data['other_permission'] = serialize($gp);
				$data['usergroup_type'] = $type;
				$api->updateGroup($gid,$data);
				$this->redirect(site_url('admin/usergroup?type='.$type),lang('200_updatesuccess','tip'));
				return;
			}else{
				$this->group = $group;
				//$this->permissions = $permissions[$type];
				$this->output('user/permission-'.$type);
				return;
			}
		}else if($act=='add'&&$type){
			$data['usergroup_name'] = $this->param('group_name');
			$data['usergroup_key'] = $this->param('group_key');
			$data['color'] = $this->param('group_color');
			$data['usergroup_type'] = $type;
			if($type=='member'){
				$data['credits_lower'] = $this->param('credits_lower');
				$data['credits_higher'] = $this->param('credits_higher');
			}
			$api->addGroup($data);
			$this->redirect(site_url('admin/usergroup?type='.$type),lang('200_updatesuccess','tip'));
			return;
		}else{
			if($type=='system'){
				$this->groups = $api->getSystemUserGroup();
			}elseif($type=='member'){
				$this->groups = $api->getMemberUserGroup();
			}elseif($type=='special'){
				$this->groups = $api->getSpecialUserGroup();
			}

			//$pager = & load_class('Pager', 'core');
			//$this->pages = $pager->createPages('admin/userlist',array('page'=>$page));
			$this->output('user/usergroup');
			return;
		}
	}

	public function starusers(){
		$act=$this->param('act');
		$starid = $this->param("starid");
		$page = $this->param("page",1);
		$db = load_db('star');
		if($starid){
			$star = $db->getStarById($starid);
		}
		if($act=='delete'&&$star){
			$db->deleteStarById($starid);
			load_db("user")->update_staruser($star['user_id'],0);
			load_db("misc/apply")->deletestarapply($star['user_id']);
			load_db("star")->update_staruser_cache();
			$this->redirect(site_url('admin/starusers'),lang('200_deletesuccess','tip'));
			return;
		}else if($act=='edit'&&$star){
			if($data['category_id'] = $this->param('category_id')){
				$postvar = array('display_order'=>'100','star_reason'=>'','category_id'=>'1');
				foreach ($postvar as $key=>$default){
					$data[$key] = $this->param($key,$default);
				}
				$db->updateStarById($starid,$data);
				$db->update_staruser_cache();
				load_db("user")->update_staruser($star['user_id'],1);
				$this->redirect(site_url('admin/starusers'),lang('200_updatesuccess','tip'));
				return;
			}else{
				$this->star = $star;
				$this->categories = load_db('star/starcategory')->getAllCategories();
				$this->output('user/star-edit');
				return;
			}
		}else{
			$this->stars = $db->search(null,$page,PAGESIZE);
			$pager = & load_class('Pager', 'core');
			$this->pages = $pager->createPages('admin/starusers',array('page'=>$page));
			$this->output('user/star');
			return;
		}
	}

	public function starcategory(){
		$act=$this->param('act');
		$catid = $this->param("catid");
		$page = $this->param("page",1);
		$db = load_db('star/starcategory');
		if($catid){
			$category = $db->getCategoryByid($catid);
		}
		if($act=='delete'&&$category){
			$db->deletecategory(array('category_id'=>$catid));
			$this->redirect(site_url('admin/starcategory'),lang('200_deletesuccess','tip'));
			return;
		}else if($act=='edit'&&$category){
			if($data['category_name'] = $this->param('category_name')){
				$data['display_order'] = $this->param('display_order');
				$data['description'] = $this->param('description');
				$db->updateCategoryByid($catid,$data);
				$this->redirect(site_url('admin/starcategory'),lang('200_updatesuccess','tip'));
				return;
			}else{
				$this->category = $category;
				$this->output('user/starcategory-edit');
				return;
			}
		}else if($act=='add'){
			$data['category_name'] = $this->param('category_name');
			$data['display_order'] = $this->param('display_order');
			$data['description'] = $this->param('description');
			$db->create($data);
			$this->redirect(site_url('admin/starcategory'),lang('200_updatesuccess','tip'));
			return;
		}else{
			$this->categories = $db->search($page,PAGESIZE);
			$pager = & load_class('Pager', 'core');
			$this->pages = $pager->createPages('admin/starcategory',array('page'=>$page));
			$this->output('user/starcategory');
			return;
		}
	}

	public function stores(){
		$act=$this->param('act');
		$storeid = $this->param("storeid");
		$page = $this->param("page",1);
		$db = load_api('store');
		if($storeid){
			$store = $db->getStoreByid($storeid);
		}
		if($act=='delete'&&$store){
			$db->delete($storeid);
			$this->redirect(site_url('admin/stores'),lang('200_deletesuccess','tip'));
			return;
		}else if($act=='edit'&&$store){
			if($data['category_id'] = $this->param('category_id')){
				$postvar = array('display_order'=>'100','store_reason'=>'','category_id'=>'1');
				foreach ($postvar as $key=>$default){
					$data[$key] = $this->param($key,$default);
				}
				load_db("store")->updateStoreByid($storeid,$data);
				$this->redirect(site_url('admin/stores'),lang('200_updatesuccess','tip'));
				return;
			}else{
				$this->store = $store;
				$this->categories = load_db('store/storecategory')->getAllCategories();
				$this->output('user/store-edit');
				return;
			}
		}else{
			$this->stores = load_db("store")->search(null,$page,PAGESIZE);
			$pager = & load_class('Pager', 'core');
			$this->pages = $pager->createPages('admin/stores',array('page'=>$page));
			$this->output('user/store');
			return;
		}
	}

	public function storecategory(){
		$act=$this->param('act');
		$catid = $this->param("catid");
		$page = $this->param("page",1);
		$db = load_db('store/storecategory');
		if($catid){
			$category = $db->getCategoryByid($catid);
		}
		if($act=='delete'&&$category){
			$db->deletecategory(array('category_id'=>$catid));
			$this->redirect(site_url('admin/storecategory'),lang('200_deletesuccess','tip'));
			return;
		}else if($act=='edit'&&$category){
			if($data['category_name'] = $this->param('category_name')){
				$data['display_order'] = $this->param('display_order');
				$data['topics'] = $this->param('topics');
				$db->updateCategoryByid($catid,$data);
				$this->redirect(site_url('admin/storecategory'),lang('200_updatesuccess','tip'));
				return;
			}else{
				$this->category = $category;
				$this->output('user/storecategory-edit');
				return;
			}
		}else if($act=='add'){
			$data['category_name'] = $this->param('category_name');
			$data['display_order'] = $this->param('display_order');
			$data['topics'] = $this->param('topics');
			$db->add_one($data);
			$this->redirect(site_url('admin/storecategory'),lang('200_updatesuccess','tip'));
			return;
		}else{
			$this->categories = $db->search($page,PAGESIZE);
			$pager = & load_class('Pager', 'core');
			$this->pages = $pager->createPages('admin/storecategory',array('page'=>$page));
			$this->output('user/storecategory');
			return;
		}
	}

	public function apply(){
		$act=$this->param('act');
		$this->type = $this->param("type");
		$apid = $this->param("apid");
		$this->status = $this->param("status");
		$page = $this->param("page",1);
		$db = load_db('misc/apply');
		if($apid){
			$apply = $db->getapplybyid($apid);
		}
		if($act=='delete'&&$apply){
			$db->deleteapply(array('apply_id'=>$apid));
			$this->redirect(site_url('admin/apply'),lang('200_deletesuccess','tip'));
			return;
		}else if($act=='agree'&&$apply){
			$db->agree($apid);
			$this->redirect(site_url('admin/apply?type='.$this->type),lang('200_updatesuccess','tip'));
			return;
		}else if($act=='disagree'&&$apply){
			$db->disagree($apid);
			$this->redirect(site_url('admin/apply?type='.$this->type),lang('200_updatesuccess','tip'));
			return;
		}else if($act=='recusal'&&$apply){
			$db->recusal($apid);
			$this->redirect(site_url('admin/apply?type='.$this->type),lang('200_updatesuccess','tip'));
			return;
		}else{
			$applies = $db->search($this->type,$this->status,$page,PAGESIZE);
			foreach ($applies as $key=>$apply){
				if($apply['apply_type']==2){
					$store = load_db('store')->find(array('store_id'=>$apply['rel_id']));
					$applies[$key]['store'] = $store;
				}
			}
			$this->applies = $applies;
			$pager = & load_class('Pager', 'core');
			$this->pages = $pager->createPages('admin/apply',array('page'=>$page));
			$this->output('user/apply');
			return;
		}
	}

	public function misccache(){
		$act=$this->param('act');
		$cache=$this->param('cache');
		$api = load_api('setting');
		if($act=='save'){
			load_helper('file');
			if(in_array('tpl', $cache)){
				//delete_files(BASEPATH.'data/template/');
				delete_files(BASEPATH.'data/template/', FALSE, 0, 'php');
				delete_files(BASEPATH.'data/template/', FALSE, 0, 'js');
			}
			if(in_array('data', $cache)){
				delete_files(BASEPATH.'data/cache/');
			}
			if(in_array('css', $cache)){
				$settings = $api->getGlobalSetting();
				$this->template->updateless('boot',$settings['style'],'default',1);
				$styles = $api->getStyleSetting();
				if($styles[$settings['style']]){
					foreach($styles[$settings['style']] as $key=>$color){
						$this->template->updateless('boot',$settings['style'],$key,1);
					}
				}

			}
			$this->redirect(site_url('admin/misccache'),lang('200_updatesuccess','tip'));
			return;

		}else{
			$this->output('misc/cache');
			return;
		}
	}


	public function recreate(){
		$act=$this->param('act');
		$page=$this->param('page',1);
		if($act=='album'){
			$api = load_api('album');
			$albums = $api->search(null,$page,100,' ptx_album.create_time DESC ');
			foreach ($albums as $album){
				$api->update_album_cover($album['album_id']);
			}
			if($albums&&array_length($albums)>0){
				$start=($page-1)*100;
				$end=$start+100;
				$this->redirect(site_url('admin/recreate?act=album&page='.($page+1)), lang('recreate_album_tip','admin')." {$start} to {$end}");
			}else{
				$this->redirect(site_url('admin/recreate'), lang('200_updatesuccess','tip'));
			}
		}elseif($act=='itemdetail'){
			$items = load_db('share/item')->search(null,$page,100," ptx_item.item_id,ptx_item.promotion_url ",NULL);
			$itemdetaildb = load_db('share/itemdetail');
			foreach ($items as $item) {
				if($itemdetaildb->findbyid($item['item_id'])){
					continue;
				}else{
					$datadetail = array();
					$datadetail['item_id']=$item['item_id'];
					$datadetail['intro']=$item['intro'];
					$datadetail['intro_search']=$item['intro_search'];
					$datadetail['reference_url']=$item['reference_url'];
					$datadetail['reference_itemid']=$item['reference_itemid'];
					$datadetail['promotion_url']=pzxencode(str_replace('+', '%2B', $item['promotion_url']));
					$itemdetaildb->addone($datadetail);
				}
			}
			if($items&&array_length($items)>0){
				$start=($page-1)*100;
				$end=$start+100;
				$this->redirect(site_url('admin/recreate?act=itemdetail&page='.($page+1)), lang('recreate_album_tip','admin')." {$start} to {$end}");
			}else{
				$this->redirect(site_url('admin/recreate'), lang('200_updatesuccess','tip'));
			}
		}elseif($act=='category'){
			load_api('category')->check_totalshare();
			$this->redirect(site_url('admin/recreate'), lang('200_updatesuccess','tip'));
			return;
		}else{
			$this->output('misc/recreate');
			return;
		}
	}

	public function homeslide(){
		$act = $this->param("act");
		$settingapi = load_api('setting');
		$settingkey = 'homeslide';
		$homeslide = $settingapi->getSetting($settingkey);
		if($act=='add'){
			if($image_url = $this->param("filename")){
				$slide_image = array(
						'key'=>TIMESTAMP,
						'image_url'=>'data/attachments/homeslide/'.$image_url,
						'link_url'=>$this->param("link_url"),
						'order'=>$this->param("order"),
						'title'=>$this->param("title"),
						'desc'=>$this->param("desc")
				);

				if(!is_array($homeslide)){
					$homeslide = array();
				}
				array_push($homeslide, $slide_image);
				$homeslide = sysSortArray($homeslide, 'order', 'SORT_ASC','SORT_NUMERIC');
				$settingapi->updateSetting($settingkey,$homeslide);
				$this->redirect(site_url('admin/homeslide'), lang('operate_success','admin'));
			}
		}elseif($act=='edit'){
			$key = $this->param("key");
			foreach ($homeslide as $slide){
				if($slide['key'] == $key){
					$slide_edit = $slide;
					break;
				}
			}
			$this->slide = $slide_edit;
			$this->output("operation/homeslide-edit");
			return;
		}elseif($act=='edit_submit'){
			$key = $this->param("key");
			$image_url = $this->param("filename");
			foreach ($homeslide as $i=>$slide){
				if($slide['key'] == $key){
					$index = $i;
					break;
				}
			}
			$homeslide[$index]['link_url'] = $this->param("link_url");

			if($image_url){
				$image_url = 'data/attachments/homeslide/'.$image_url;
				file_exists(BASEPATH.$homeslide[$index]['image_url']) && unlink(BASEPATH.$homeslide[$index]['image_url']);
				$homeslide[$index]['image_url'] = $image_url;
			}
			$homeslide[$index]['order'] = $this->param("order");
			$homeslide[$index]['desc'] = $this->param("desc");
			$homeslide[$index]['title'] = $this->param("title");
			$homeslide = sysSortArray($homeslide, 'order', 'SORT_ASC','SORT_NUMERIC');

			$settingapi->updateSetting($settingkey,$homeslide);
			$this->redirect(site_url('admin/homeslide'), lang('operate_success','admin'));
			return;
		}elseif($act=='upload'){
			$attachmentapi = load_api('attachment');
			$settings =  $this->settings;
			$allowedExtensions = array('jpg','jpeg','gif','png');
			$sizeLimit = 2 * 1024 * 1024;
			$temp_dir = BASEPATH.'data/attachments/homeslide/';
			(!is_dir($temp_dir))&&@mkdir($temp_dir,0777,true);
			$result = $attachmentapi->simpleUpload($temp_dir,false,$allowedExtensions,$sizeLimit);
			$this->ajax_response($result);
			return;
		}elseif($act=='delete'){
			$key = $this->param("key");
			foreach ($homeslide as $i=>$slide){
				if($slide['key'] == $key){
					$index = $i;
					$image_url = $slide['image_url'];
					break;
				}
			}
			array_splice($homeslide, $index,1);
			if($image_url){
				file_exists(BASEPATH.$image_url) && unlink(BASEPATH.$image_url);
			}
			$settingapi->updateSetting($settingkey,$homeslide);
			$this->redirect(site_url('admin/homeslide'), lang('operate_success','admin'));
			return;
		}else{
			$this->slides = $homeslide?$homeslide:array();
			$this->output("operation/homeslide");
		}
	}

	public function adsmanage(){
		$action = $this->param("act");
		$settingapi = load_api('setting');
		$settingkey = 'ads';
		$setting = $settingapi->getSetting($settingkey);
		$this->positions = array('homepage_ad','pinpage_ad','detailpage_ad');
		if($action=='add'){
			$ad_position = $this->param("ad_position");
			if(in_array($ad_position, $this->positions)){
				$ads = array();
				$ads['key']= TIMESTAMP;
				$ads['ad_name'] = $this->param("ad_name");
				$ads['width'] = $this->param("width");
				$ads['height'] = $this->param("height");
				$ads['position'] = $ad_position;
				$ads['ad_source'] = stripslashes($this->param("ad_source",'',false));
				$setting[$ad_position] = (is_array($setting[$ad_position]))?$setting[$ad_position]:array();
				array_push($setting[$ad_position], $ads);
				$settingapi->updateSetting($settingkey,$setting);
			}
			$this->redirect(site_url('admin/adsmanage'), lang('operate_success','admin'));
		}else if($action=='edit'){
			$key = $this->param("key");
			$ad_position = $this->param("ad_position");
			if(in_array($ad_position, $this->positions)){
				$ads_array = $setting[$ad_position];
				foreach ($ads_array as $ads){
					if($ads['key'] == $key){
						$ads_edit = $ads;
						break;
					}
				}
				$ads_edit['ad_position']=$ad_position;
				$this->ads_edit = $ads_edit;
				$this->output("operation/adsmanage-edit");
			}
		}else if($action=='edit_submit'){
			$key = $this->param("key");
			$ad_position = $this->param("ad_position");
			if(in_array($ad_position, $this->positions)){
				$ads_array = $setting[$ad_position];
				foreach ($ads_array as $i=>$ads){
					if($ads['key'] == $key){
						$index = $i;
						break;
					}
				}
				$setting[$ad_position][$index]['key']= mktime();
				$setting[$ad_position][$index]['ad_name'] = $this->param("ad_name");
				$setting[$ad_position][$index]['width'] = $this->param("width");
				$setting[$ad_position][$index]['height'] = $this->param("height");
				$setting[$ad_position][$index]['position'] = $ad_position;
				$setting[$ad_position][$index]['ad_source'] = stripslashes($this->param("ad_source",'',false));
				$settingapi->updateSetting($settingkey,$setting);
			}
			$this->redirect(site_url('admin/adsmanage'), lang('operate_success','admin'));
			return;
		}else if($action=='delete'){
			$key = $this->param("key");
			$ad_position = $this->param("ad_position");
			if(in_array($ad_position, $this->positions)){
				$ads_array = $setting[$ad_position];
				foreach ($ads_array as $i=>$ads){
					if($ads['key'] == $key){
						$index = $i;
						break;
					}
				}
				array_splice($setting[$ad_position], $index,1);
				$settingapi->updateSetting($settingkey,$setting);
			}
			$this->redirect(site_url('admin/adsmanage'), lang('operate_success','admin'));
		}else{
			$this->homepage_ads = $setting['homepage_ad'];
			$this->pinpage_ads = $setting['pinpage_ad'];
			$this->detailpage_ads = $setting['detailpage_ad'];
			$this->output("operation/adsmanage");
		}
	}


	public function friendlink(){
		$api = load_api('setting');
		$setting = $api->getSetting('global');
		$act=$this->param('act');
		$friendlinks = $setting['friendlink'];
		if($act=='add'){
			if($link_url = $this->param("url")){
				$link = array(
						'key'=>mktime(),
						'url'=>$link_url,
						'name'=>$this->param("name")
				);
				if(!is_array($friendlinks)){
					$friendlinks = array();
				}
				array_push($friendlinks, $link);
				$setting['friendlink'] = $friendlinks;
				$api->updateSetting('global',$setting);
				$this->redirect(site_url('admin/friendlink'), lang('operate_success','admin'));
			}
			return;
		}elseif($act=='delete'){
			$key = $this->param("key");
			foreach ($friendlinks as $i=>$frindlink){
				if($frindlink['key'] == $key){
					$index = $i;
					break;
				}
			}
			array_splice($friendlinks, $index,1);
			$setting['friendlink'] = $friendlinks;
			$api->updateSetting('global',$setting);
			$this->redirect(site_url('admin/friendlink'), lang('operate_success','admin'));
		}else{
			$this->links = $friendlinks?$friendlinks:array();
			$this->output("operation/friendlink");
		}
	}


	public function writeGatherCache($items){
		$arr = array();
		if($items&&is_array($items['items'])){
			foreach ($items['items'] as $item) {
				$arr[]=serialize($item);
			}
			pcache('w','gatherCache',$arr);
		}
		return $arr;
	}


	public function readGatherCache($numiid){
		$result = pcache('r', 'gatherCache');
		if($result){
			foreach ($result as $item){
				$item = unserialize($item);
				if($numiid==$item->num_iid){
					return $item;
				}
			}
		}
		return null;
	}


	private function prepareItem($postdata){
		$puzzcode = load_api('puzzcode');
		$api = load_api('setting');

		$keyword = str_replace('  ', ' ', $postdata['keyword']);
		$intro_search = $plaintxt = $puzzcode->parse_plain_message($postdata['text']);
		$setting = $api->getSetting('share');
		$tagnum = $setting['tagnum'];
		$isshow = '1';
		$nowtagnum = array_length(explode(' ', $keyword));
		if($nowtagnum<$tagnum){
			$tagapi = load_api('tag');
			$collected = $tagapi->collectFromTxt($postdata['category_id'],$postdata['title'].$plaintxt,$tagnum-$nowtagnum);
			$collected = join(' ', $collected);
			$keyword .= ' '.$collected;
			$keyword = str_replace('  ', ' ', $keyword);
		}

		$keyword_search = $keyword;
		if($this->isChineseVersion()){
			$segment = &load_class('Segment');
			$keyword_search = $segment->convert_to_py($keyword_search);
			$segment_str = $segment->segment($plaintxt);
			$intro_search = $segment_str['py'];
		}

		$parseat_str = $puzzcode->parse_at($postdata['text']);
		$parsetopic_str = $puzzcode->parse_topic($parseat_str['message']);

		$user = $this->cuser;
		$data['user_id']=$user['uid'];
		$data['user_nickname']=$user['nickname'];
		$data['title'] = isset($postdata['title']) ? dhtmlspecialchars(trim($postdata['title'])) : '';
		$data['title'] = !empty($postdata['title']) ? delete_html(str_replace("\t", ' ', $postdata['title'])) : $postdata['title'];
		$data['keyword']=$keyword;
		$data['keyword_search']=$keyword_search.' '.$parseat_str['atsearch_str'].' '.$parsetopic_str['search_str'];
		$data['color']='';
		$data['image_path_0']='';
		$data['image_path_1']='';
		$data['image_path_2']='';
		$data['width']='';
		$data['height']='';
		$data['item_type']=$postdata['item_type'];
		$data['share_type']=$postdata['share_type'];
		$data['price']=$postdata['price'];
		$data['is_show']=$isshow;
		$data['total_images']='';
		$data['summary']=sysSubStr($plaintxt, 500, TRUE);

		$datadetail['intro']=delete_html($parsetopic_str['message']);
		$datadetail['intro_search']=$intro_search.' '.$parseat_str['atsearch_str'].' '.$parsetopic_str['search_str'];
		$datadetail['reference_url']=$postdata['url'];
		$datadetail['reference_itemid']=$postdata['reference_itemid'];
		$datadetail['promotion_url']=$postdata['promotion_url'];

		$datashare['poster_id']=$user['uid'];
		$datashare['poster_nickname']=$user['nickname'];
		$datashare['user_id']=$user['uid'];
		$datashare['user_nickname']=$user['nickname'];
		$datashare['category_id']=$postdata['category_id'];
		$datashare['album_id']=$postdata['album_id'];
		$data['itemdetail'] = $datadetail;
		$data['sharedata'] = $datashare;

		$shareapi = load_api('share');
		$itemid = $shareapi->addOriginalShare($data);
		return $itemid;
	}

	private function processfetchs($data){
		$return = false;
		if($data['fetchs']){
			$fetchs = $data['fetchs'];
			foreach ($fetchs as $img){
				$url = $img['url'];
				$image = $img['image'];
				$cover = $img['cover'];
				$desc = $img['desc'];
				$type = $img['type'];
					
				$api = load_api('attachment');
				if($att = $api->saveRemoteImage($image,$url,$data['item_id'],$desc,$cover)){
					if($cover&&!$return['findcover']){
						$return['findcover']=true;
						$return['attachment']=$att['attachment'];
						$return['item_type']='image';
						$return['fileext']=$att['fileext'];
						$return['width']=$att['width'];
						$return['height']=$att['height'];
						$return['share_type']=$type;
						$return['aid']=$att['aid'];
					}
					$return['remoteimgs'][] = $att;
				}
			}
			$return['total'] = array_length($fetchs);
		}
		return $return;
	}

	private function save_share_fetch($item,$iscache){
		//num_iid,title,nick,pic_url,price,click_url,commission,commission_rate,commission_volume,commission_num,volume

		if($iscache){
			$postdata['text'] = $item['cache']->title;
			$postdata['price'] = $item['cache']->price;
			$postdata['title'] = $item['cache']->title;
			$postdata['promotion_url'] = pzxencode($item['cache']->click_url);
			$postdata['reference_itemid'] = $item['cache']->num_iid;
			$postdata['category_id'] = $item['category_id'];
			$postdata['album_id'] = $item['album_id'];
			$postdata['share_type'] = 'taobao';
			$postdata['item_type'] = 'image';
			$image['image'] = $item['cache']->pic_url;
			$image['cover'] = true;
			$image['desc'] = '';
			$image['type'] = 'taobao';
			$postdata['fetchs'][] = $image;
		}else{
			$postdata['text'] = $item['desc'];
			$postdata['price'] = $item['price'];
			$postdata['title'] = $item['title'];
			$postdata['url'] = $item['url'];
			$postdata['promotion_url'] = $item['prourl'];
			$postdata['reference_itemid'] = $item['id'];
			$postdata['category_id'] = $item['category_id'];
			$postdata['album_id'] = $item['album_id'];
			$postdata['share_type'] = 'taobao';
			$postdata['item_type'] = 'image';

			foreach ($item['images'] as $key=>$up_image){
				$image['image'] = $up_image['imageurl'];
				$image['desc'] = '';
				$image['type'] = 'taobao';
				$image['url'] = $item['url'];
				if($up_image['imageurl']==$item['orgin_image_url']){
					$image['cover'] = true;
				}
				$postdata['fetchs'][] = $image;
			}
		}
		$itemid = $this->prepareItem($postdata);
		$postdata['item_id'] = $itemid;
		$results[] = $this->processfetchs($postdata);
		$cover = array();
		$total = 0;
		foreach ($results as $r){
			$total += $r['total'];
			if($r['findcover']){
				$cover = $r;
			}
		}
		$cover['total'] = $total;
		if($fetchs['total']>0){
			$cover['remoteimgs'] = $fetchs['remoteimgs'];
		}
		if(load_api('share')->updateItem($cover, $itemid)){
			load_api('attachment')->deleteUnusedByUser($this->cuser['uid']);
			load_api('album')->update_album_cover($item['album_id']);
		}
		load_db('user')->add_share($this->cuser['uid']);
		return true;
	}

	public function taobaogather(){
		$act = $this->param("act");
		$this->page = $this->param("page",1);
		$channel = load_api("channel/taobao");
		if($act=='search'){
			$this->keyword = $this->param("keyword");
			$this->channel_category_id = $this->param("channel_category_id",0);
			$param['channel_category_id'] = $this->channel_category_id;
			$param['keyword'] = $this->keyword;
			$param['page'] = $this->page;
			$param['num_per_page'] = 40;
			$this->items = $channel->search_gathering($param);
			$this->writeGatherCache($this->items);
			$args = array();
			$args['channel_category_id'] = $this->channel_category_id;
			if($this->keyword) $args['keyword'] = $this->keyword;
			$args['page'] = $this->page;
			$args['act'] = 'search';
			$this->pages = mpages('admin/taobaogather', $this->items['total_results'], 40, $this->page, $args);
		}elseif($act=='publish'){
			$num_iid_str = $this->param("num_iid_str");
			$category_id = $this->param("category_id");
			$album_id = $this->param("album_id");
			$morepic = $this->param("morepic",'0');
			$num_iid_arr = explode(',', $num_iid_str);
			foreach ($num_iid_arr as $num_iid){
				//$pinfo = $channel->fetch_goodinfo($channel_name,$num_iid);
				if($num_iid!='on'&&$num_iid&&is_numeric($num_iid)){
					if($morepic){
						$pinfo = $channel->fetch_goodinfo($num_iid);
						$pinfo['category_id'] = $category_id;
						$pinfo['album_id'] = $album_id;
						$iscache = false;
					}else{
						$cache = $this->readGatherCache($num_iid);
						if($cache){
							$pinfo['category_id'] = $category_id;
							$pinfo['album_id'] = $album_id;
							$pinfo['cache'] = $cache;
							$iscache = true;
						}
					}
					if($pinfo){
						$this->save_share_fetch($pinfo,$iscache);
					}
				}
			}
			$this->ajax_success_response(null,lang('operate_success','admin').' total '.array_length($num_iid_arr));
			return;
		}elseif($act=='fetch_category'){
			$channel_categories = $channel->fetch_categories(0);
			$this->ajax_success_response($channel_categories);
			return;
		}
		$this->output("operation/taobaogather");
	}

	public function taobaorule(){
		$api = load_api('setting');
		$settingkey = 'taobaorule';
		$setting = $api->getSetting($settingkey);
		$act=$this->param('act');
		if($act=='save'){
			$rule_setting = array('start_price'=>1,'end_price'=>99999,'auto_send'=>'NAN','area'=>'NAN'
					,'start_credit'=>'1heart','end_credit'=>'5goldencrown','sort'=>'commissionRate_desc','guarantee'=>'NAN','start_commissionRate'=>'NAN'
					,'end_commissionRate'=>'NAN','start_commissionNum'=>'NAN','end_commissionNum'=>'NAN','start_totalnum'=>'NAN','end_totalnum'=>'NAN');
			foreach ($rule_setting as $key=>$value){
				$setting[$key] = $this->param($key,$value);
			}
			$api->updateSetting($settingkey,$setting);
			$this->redirect(site_url('admin/taobaorule'), lang('operate_success','admin'));
			return;
		}
		$this->setting = $setting;
		$this->output('operation/taobaorule');
	}

	public function versioncheck(){
		$vlink = "http://www.onightjar.com/index.php?c=pzupgrade&a=lastestversion";
		$json = get_contents($vlink);

		$content = json_decode($json);
		$localversion = config_item('pzversion','version');
		$localrelease = config_item('pzrelease','version');
		if($content->data->pzrelease>$localrelease){
			$this->ajax_success_response(array('link'=>$content->data->pzdlink),lang('new_version_available','admin'));
			return;
		}

		$this->ajax_failed_response(lang('no_need_upgrade','admin'));
		return;
	}

	function sysupdate(){
		$localversion = config_item('pzversion','version');
		$localrelease = config_item('pzrelease','version');
		$vlink = "http://www.onightjar.com/index.php?c=pzupgrade&a=patches&pzversion={$localversion}&pzrelease={$localrelease}";
		$json = get_contents($vlink);

		$this->releases = json_decode($json,true);

		$this->output('misc/sysupdate');
	}

	function modulemanage(){
		$sysmodules = array('admin','album','attachment','category','censor','channel','comment','detail','email','event','faq','forum',
				'group','home','install','message','misc','pin','puzzcode','search','setting','share','social','star','store',
				'tag','topic','ucenter','upgrade','user','welcome','mmg');
		$act = $this->param("act");
		$md = $this->param("md");
		if($act=='install'){
			$mmg = load_api('mmg');
			if(!in_array($md, $sysmodules)){
				if($mmg->install($md)){
					$this->redirect(site_url('admin/modulemanage'), lang('operate_success','admin'));
					return;
				}
			}
			$this->message(lang('error','tip'), lang('500_operatefaild','tip'));
			return;
		}else if($act=='uninstall'){
			$mmg = load_api('mmg');
			if(!in_array($md, $sysmodules)){
				if($mmg->uninstall($md)){
					$this->redirect(site_url('admin/modulemanage'), lang('operate_success','admin'));
					return;
				}
			}
			$this->message(lang('error','tip'), lang('500_operatefaild','tip'));
			return;
		}else{
			load_helper('file');
			$locals_dir = APPPATH.'modules/';
			$file_list = get_dir_file_info($locals_dir);
			$api = load_api('setting');
			$settingkey = 'modules';
			$setting = $api->getSetting($settingkey);
			$modules = array();
			foreach ($file_list as $d) {
				if(!in_array($d['name'], $sysmodules)){
					$module = array();
					$module['name'] = $d['name'];
					$module['description'] = lang('description',$d['name']);
					$module['author'] = lang('author',$d['name']);
					$module['version'] = load_api($d['name'])->version;
					if($setting[$d['name']]) $module['loaded'] = true;
					$modules[] = $module;
						
				}
			}
			//$settings = $api->getGlobalSetting();

			//$api->updateSetting('global',$settings);
			$this->modules = $modules;
			$this->output('misc/modulelist');
		}

	}

	public function dbmanagement(){
		$bkdb = &load_class('dbbackup');
		$this->table =  $bkdb->showAllTable($this->param('chk',0));
		$this->output('misc/dbmanage');
	}

	public function dbbackup(){
		$bkdb = &load_class('dbbackup');
		$act = $this->param("act");
		$table = $this->param("table");
		if($act=='outall'&&$bkdb){
			$bkdb->outAllData();
		}elseif($act=='optimize'&&$bkdb&&$table){
			$bkdb->optimizeTable($table);
			$this->redirect(site_url('admin/dbmanagement'), lang('operate_success','admin'));
		}elseif($act=='repair'&&$bkdb&&$table){
			$bkdb->repairTable($table);
			$this->redirect(site_url('admin/dbmanagement'), lang('operate_success','admin'));
		}elseif($act=='outone'&&$bkdb&&$table){
			$bkdb->outTable($table);
		}
	}

	public function dbdownload(){
		load_helper('download');
		$file_name = $this->param('fname');
		$dbbackup_dir = BASEPATH.'data/database';
		$data = file_get_contents($dbbackup_dir."/".$file_name);
		force_download($file_name, $data);
	}

	public function dzucenter(){
		$act = $this->param("act");
		$settingapi = load_api('setting');
		$settingkey = 'dzucenter';
		$setting = $settingapi->getSetting($settingkey);
		if($act=='save'){
			$postvar = array('UC_OPEN'=>'0','UC_API'=>'','UC_DBHOST'=>'','UC_DBNAME'=>'','UC_DBTABLEPRE'=>'','UC_DBUSER'=>'','UC_DBPW'=>'','UC_APPID'=>'1','UC_KEY'=>'');
			foreach ($postvar as $k=>$default){
				$setting[$k] = $this->param($k,$default,false);
			}
			$settingapi->updateSetting($settingkey,$setting);
			load_helper('configfile');
			$default_config = $config = array();
			$default_configfile = BASEPATH.'config/uc_default.php';

			if(!file_exists($default_configfile)) {
				exit('uc_default.php was lost, please reupload this  file.');
			} else {
				include $default_configfile;
				$default_config = $config;
			}

			$config=$setting;

			save_config_file(BASEPATH.'config/uc.php', $config, $default_config);
			$this->redirect(site_url('admin/dzucenter'),lang('200_updatesuccess','tip'));
			return;
		}else{
			$this->setting = $setting;
			$this->output('dz/ucenter');
		}
	}

	public function dzforum(){
		$act = $this->param("act");
		$settingapi = load_api('setting');
		$settingkey = 'dzforum';
		$setting = $settingapi->getSetting($settingkey);
		if($act=='save'){
			$postvar = array('open'=>'0','hostname'=>'0','username'=>'','password'=>'','database'=>'','dbprefix'=>'');
			foreach ($postvar as $k=>$default){
				$setting[$k] = $this->param($k,$default,false);
			}
			$settingapi->updateSetting($settingkey,$setting);
			load_helper('configfile');
			$default_config = $config = array();
			$default_configfile = BASEPATH.'config/database.php';

			if(!file_exists($default_configfile)) {
				exit('database.php was lost, please reupload this  file.');
			} else {
				include $default_configfile;
				$default_config = $config;
			}

			$config['bbs']=$setting;

			save_config_file(BASEPATH.'config/database.php', $config, $default_config);
			$this->redirect(site_url('admin/dzforum'),lang('200_updatesuccess','tip'));
			return;
		}else{
			$this->setting = $setting;
			$this->output('dz/forum');
		}
	}

	public function load(){
		$pm = $this->param("pm");
		$act = $this->param("act");
		if($pm){
			$api = load_api($pm.'/'.$pm.'_admin');
			return $api->$act();
		}
	}
}

function mpages($link,$total_count, $perpage, $curpage,$args,$pkey='page'){

	$totalpage = @ceil($total_count / $perpage);
	if($totalpage==1)
		return '';

	$page_for_pageData = min(intval(max($curpage, 1)), $total_count);
	$numpages = 10;
	$midpage = $numpages/2;
	$currentpage = $curpage;
	$lastpage = $totalpage;
	$nextpage = ( ( $currentpage == $total_page ) ? $total_page : ($currentpage + 1));
	$prevpage = ( ( 1 == $currentpage ) ? 1 : ($currentpage - 1) );
	$firstpage = 1;

	$des = '<div class="pagination"><ul>';
	if ($currentpage != $firstpage&&$prevpage>0){
		$args[$pkey] = $prevpage;
		$des .= '<li><a href="'.site_url_param($link,$args).'">'.lang('prev_page').'</a></li>';
	}

	if($totalpage>$numpages){
		if($currentpage<$midpage){
			for ($i=0;$i<$numpages;$i++){
				$pnum = ($i+1);
				if ($pnum != $currentpage) {
					$args[$pkey] = $pnum;
					$des .= '<li><a href="'.site_url_param($link,$args).'">'.$pnum.'</a></li>';
				}else{
					$des .= '<li class="active"><a href="javascript:;">'.$pnum.'</a></li>';
				}
			}

		}else{
			$start = $currentpage-$midpage;
			$end = $currentpage+$midpage;
			$end = ($end+1<=$lastpage)?$end:($lastpage);
			if($start>0){
				$args[$pkey] = $firstpage;
				$des .= '<li><a href="'.site_url_param($link,$args).'">1...</a></li>';
			}
			for ($i=$start;$i<$end;$i++){
				$pnum = ($i+1);
				if ($pnum != $currentpage) {
					$args[$pkey] = $pnum;
					$des .= '<li><a href="'.site_url_param($link,$args).'">'.$pnum.'</a></li>';
				}else{
					$des .= '<li class="active"><a href="javascript:;">'.$pnum.'</a></li>';
				}
			}
		}
		$off = $currentpage+$midpage;
		if($off&&($off<$lastpage)){
			$args[$pkey] = $lastpage;
			$des .= '<li><a href="'.site_url_param($link,$args).'">...'.$lastpage.'</a></li>';
		}

	}else{
		for ($i=0;$i<$totalpage;$i++){
			$pnum = ($i+1);
			if ($pnum != $currentpage) {
				$args[$pkey] = $pnum;
				$des .= '<li><a href="'.site_url_param($link,$args).'">'.$pnum.'</a></li>';;
			}else{
				$des .= '<li class="active"><a href="javascript:;">'.$pnum.'</a></li>';
			}
		}
	}

	if ($pager['current_page'] != $lastpage){
		$args[$pkey] = $nextpage;
		$des .= '<li><a href="'.site_url_param($link,$args).'">'.lang('next_page').'</a></li>';
	}
	$des .= '</ul></div>';
	return $des;
}